package com.suning.sawp.service.impl.util;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import net.oss.client.OSSClient;
import net.oss.client.OSSClientImpl;
import net.oss.result.SdossResult;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.suning.sawp.intf.util.OSSImgService;
import com.suning.sawp.po.util.OSSResult;

/**
 * OSS文件存储工具类 API ：http://wiki.cnsuning.com/pages/viewpage.action?pageId=27238154
 * 平台：http://osspsit.cnsuning.com/snoss-web/ http://osspprd.cnsuning.com/snoss-web/
 * 
 * @author 15050769
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Service
public class OSSImgServiceImpl implements OSSImgService {
    private static final Logger LOGGER = LoggerFactory.getLogger(OSSImgServiceImpl.class);

    // 企业会员bucketname
    private static final String BUCKET_CM = "snsawp_companmen";
    
    /**
     * oss配置文件地址
     */
    @Value("#{settingConfig[oss_config_path]}")
    String OSS_CONFIG_PATH;

    @Override
    public OSSResult upload2Oss(String bucket, String objectname, String mimeType ,InputStream in) {
        LOGGER.info("authority error for bucket :{},objectname :{} ", bucket, objectname);
        if (StringUtils.isBlank(objectname)) {
            return null;
        }
        
        OSSResult oSSResult = new OSSResult();
        // 设置默认BUCKET
        String bucketnameInput = StringUtils.isBlank(bucket) ? BUCKET_CM : bucket;

        OSSClient client = new OSSClientImpl(false,OSS_CONFIG_PATH);
        Map<String, String> headerArgument = new HashMap<String, String>();
        try {
            // 获取鉴权
            SdossResult authorityReturn = client.putObject(bucketnameInput, objectname, headerArgument);

            String url = authorityReturn.getFileraddr() + "/" + authorityReturn.getAccount_id() + "/" + bucketnameInput
                    + "/" + objectname; // objectname必须和生成签名时一致
            if (authorityReturn != null && authorityReturn.isSuccess()) {
                // 上传文件
                SdossResult result = client.putObject(in, objectname, mimeType, headerArgument,
                        authorityReturn.getAuthorization(), authorityReturn.getCurrent_time(), url);
                if (result.isSuccess()) {
                    // 获取下载URL
                  String returnUrl = authorityReturn.getFileraddr() + "/" + authorityReturn.getAccount_id() + "/"
                            + bucketnameInput + "/" + result.getObjectId();
                  oSSResult.setImgUrl(returnUrl);
                  String returnUrl1 = authorityReturn.getFileraddr() + "/" +authorityReturn.getAccount_id() + "/" + bucketnameInput + "/" + result.getObjectId() + "?format=690h_690w_80Q";
                  oSSResult.setThumbnailUrl(returnUrl1);
                } else {
                    LOGGER.error("putObject error for bucket :{},objectname :{} ", bucket, objectname);
                }
            } else {
                LOGGER.error("authority error for bucket :{},objectname :{} ", bucket, objectname);
            }
        } catch (Exception e) {
            LOGGER.error("authority exception ", e);
            return null;
        } finally {
            IOUtils.closeQuietly(in);
        }

        return oSSResult;
    }

}
